package com.example.myapplication.view;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.provider.MediaStore;
import android.provider.Settings;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import androidx.activity.EdgeToEdge;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;

import com.example.myapplication.dao.MySQLConnection;
import com.example.myapplication.R;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationServices;
import java.io.ByteArrayOutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class Test1 extends AppCompatActivity {
    private MySQLConnection dbConnection;
    private EditText etPointId, etPointname,etRecordTime, etOutcrop, etPointMeaning, etDescription;
    private EditText etgpsLongitude, etgpsLatitude;
    private Button btnGetGps, btnTakePhoto, btnInsert,btnUpdate, btnConnect, btnDisconnect,btnDelete;
    private FusedLocationProviderClient fusedLocationClient;
    private double longitude, latitude;
    private byte[] photo;
    private ExecutorService executor;/////////////////////////////////////////////
    private ActivityResultLauncher<Intent> cameraLauncher;//这个是权限
    private ActivityResultLauncher<String[]> permissionLauncher;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);

            setContentView(R.layout.test_1);


        dbConnection = new MySQLConnection();
        executor = Executors.newSingleThreadExecutor();
        fusedLocationClient = LocationServices.getFusedLocationProviderClient(this);

        // 初始化控件
        try {
            etPointId = findViewById(R.id.et_point_id);
            etPointname = findViewById(R.id.et_point_name);
            etRecordTime = findViewById(R.id.et_record_time);
            etOutcrop = findViewById(R.id.et_outcrop);
            etPointMeaning = findViewById(R.id.et_point_meaning);
            etDescription = findViewById(R.id.et_description);
            btnGetGps = findViewById(R.id.btn_get_gps);
            btnTakePhoto = findViewById(R.id.btn_take_photo);
            btnInsert = findViewById(R.id.btn_insert);
            btnConnect = findViewById(R.id.btn_connect);
            btnDisconnect = findViewById(R.id.btn_disconnect);
            btnUpdate = findViewById(R.id.btn_update);
            etgpsLatitude=findViewById(R.id.et_get_latitude);
            etgpsLongitude=findViewById(R.id.et_get_longitude);
            btnDelete = findViewById(R.id.btn_delete);
        } catch (Exception e) {
            Toast.makeText(this, "控件绑定失败: " + e.getMessage(), Toast.LENGTH_LONG).show();
            finish();
            return;
        }

        // 权限请求的注册///
        permissionLauncher = registerForActivityResult(new ActivityResultContracts.RequestMultiplePermissions(), permissions -> {//忘记看这个
            boolean locationGranted = permissions.getOrDefault(Manifest.permission.ACCESS_FINE_LOCATION, false);
            boolean cameraGranted = permissions.getOrDefault(Manifest.permission.CAMERA, false);
            if (locationGranted) {
                getGpsLocation();
            } else if (cameraGranted) {
                takePhoto();
            } else {
                Toast.makeText(this, "需要定位和相机权限", Toast.LENGTH_SHORT).show();
            }
        });

        // 相机结果处理////////
        cameraLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), result -> {
            if (result.getResultCode() == RESULT_OK && result.getData() != null) {
                Bitmap bitmap = (Bitmap) result.getData().getExtras().get("data");
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                bitmap.compress(Bitmap.CompressFormat.JPEG, 50, baos);
                photo = baos.toByteArray();
                Toast.makeText(this, "照片已拍摄", Toast.LENGTH_SHORT).show();
            }
        });

        // 按钮事件
        btnGetGps.setOnClickListener(v -> checkPermissions(true));
        btnTakePhoto.setOnClickListener(v -> checkPermissions(false));
        btnInsert.setOnClickListener(v -> insertData());
        btnUpdate.setOnClickListener(v -> updateDate());
        btnConnect.setOnClickListener(v -> connectToDatabase());
        btnDisconnect.setOnClickListener(v -> disconnectFromDatabase());
        btnDelete.setOnClickListener(v -> deleteData());
        // 自动连接
        connectToDatabase();

        // 时间选择器
        setupDateTimePicker();
    }



    private void checkPermissions(boolean isGps) {//巧妙
        boolean locationGranted = ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED;
        boolean cameraGranted = ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED;
        if (isGps && !locationGranted) {
            permissionLauncher.launch(new String[]{Manifest.permission.ACCESS_FINE_LOCATION});//回调去了
        } else if (!isGps && !cameraGranted) {
            permissionLauncher.launch(new String[]{Manifest.permission.CAMERA});
        } else {
            if (isGps) {
                getGpsLocation();
            } else {
                takePhoto();
            }
        }
    }

private void getGpsLocation() {
    // 检查权限
    if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        Toast.makeText(this, "需要定位权限", Toast.LENGTH_SHORT).show();
        permissionLauncher.launch(new String[]{Manifest.permission.ACCESS_FINE_LOCATION});
        return;
    }

    // 检查 GPS
    LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
        Toast.makeText(this, "请开启 GPS", Toast.LENGTH_SHORT).show();
        Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
        startActivity(intent);
        return;
    }

    // 拿位置
    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, new LocationListener() {
        @Override
        public void onLocationChanged(Location location) {
            if (location != null) {


                longitude = location.getLongitude();
                latitude = location.getLatitude();
                etgpsLongitude.setText(String.format("经度: %.6f", longitude));
                etgpsLatitude.setText(String.format("纬度: %.6f", latitude));
                Toast.makeText(Test1.this, "经度: " + longitude + ", 纬度: " + latitude, Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(Test1.this, "无法获取位置", Toast.LENGTH_SHORT).show();
            }
            locationManager.removeUpdates(this);
        }
    });
}


    private void takePhoto() {
        Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
            cameraLauncher.launch(takePictureIntent);
        } else {
            Toast.makeText(this, "无法打开相机", Toast.LENGTH_SHORT).show();
        }
    }

    private void setupDateTimePicker() {
        etRecordTime.setOnClickListener(v -> {
            java.util.Calendar calendar = java.util.Calendar.getInstance();
            new android.app.DatePickerDialog(this, (view, year, month, day) -> {
                calendar.set(year, month, day);
                new android.app.TimePickerDialog(this, (timeView, hour, minute) -> {
                    calendar.set(java.util.Calendar.HOUR_OF_DAY, hour);
                    calendar.set(java.util.Calendar.MINUTE, minute);
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    etRecordTime.setText(sdf.format(calendar.getTime()));
                }, calendar.get(java.util.Calendar.HOUR_OF_DAY), calendar.get(java.util.Calendar.MINUTE), true).show();
            }, calendar.get(java.util.Calendar.YEAR), calendar.get(java.util.Calendar.MONTH), calendar.get(java.util.Calendar.DAY_OF_MONTH)).show();
        });
    }

    private void insertData() {
        String pointIdStr = etPointId.getText().toString().trim();//trim()去掉前后空格
        String pointName = etPointname.getText().toString().trim();
        String timeStr = etRecordTime.getText().toString().trim();
        String outcrop = etOutcrop.getText().toString().trim();
        String pointMeaning = etPointMeaning.getText().toString().trim();
        String description = etDescription.getText().toString().trim();
        String longitude1 = etgpsLongitude.getText().toString().trim();
        String latitude1 = etgpsLatitude.getText().toString().trim();
        latitude= Double.parseDouble(latitude1.replace("纬度: ", "").trim());
        longitude= Double.parseDouble(longitude1.replace("经度: ", "").trim());
        if (pointIdStr.isEmpty() || pointName.isEmpty()||timeStr.isEmpty() || outcrop.isEmpty() || pointMeaning.isEmpty() || description.isEmpty()) {
            Toast.makeText(this, "请填写所有必填项", Toast.LENGTH_SHORT).show();
            return;
        }

        int pointId;
        try {
            pointId = Integer.parseInt(pointIdStr);
        } catch (NumberFormatException e) {
            Toast.makeText(this, "点位序号必须是数字", Toast.LENGTH_SHORT).show();
            return;
        }

        Date recordTime;
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            recordTime = sdf.parse(timeStr);
        } catch (Exception e) {
            Toast.makeText(this, "时间格式错误 (yyyy-MM-dd HH:mm:ss)", Toast.LENGTH_SHORT).show();
            return;
        }

        if (longitude == 0.0 && latitude == 0.0) {
            Toast.makeText(this, "请先获取GPS坐标", Toast.LENGTH_SHORT).show();
            return;
        }

        if (outcrop.length() > 50 || pointMeaning.length() > 50 || description.length() > 500) {
            Toast.makeText(this, "露头/点义超50字，描述超500字", Toast.LENGTH_SHORT).show();
            return;
        }

        executor.execute(() -> {
            boolean renameExists = dbConnection.isNameExists(pointName);

            boolean success = dbConnection.insert(pointId ,pointName ,recordTime, longitude, latitude, outcrop, pointMeaning, description, photo);
            runOnUiThread(() -> {
                Toast.makeText(this, success&&!renameExists ? "数据插入成功" : "数据插入失败,请尝试在查询页面检查是否重复,或者选择修改", Toast.LENGTH_SHORT).show();
                if (success) {
                    clearInputs();
                }
            });
        });
    }
    public void deleteData(){
        String name= etPointname.getText().toString().trim();
        executor.execute(() -> {
            boolean success = dbConnection.delete(name);
            runOnUiThread(() -> {
                Toast.makeText(this, success ? "数据删除成功" : "数据删除失败,请尝试联系管理", Toast.LENGTH_SHORT).show();
                if (success) {
                    clearInputs();
                }
            });
        });

    }
    public void updateDate(){

        String pointIdStr = etPointId.getText().toString().trim();//trim()去掉前后空格
        String pointName = etPointname.getText().toString().trim();
        String timeStr = etRecordTime.getText().toString().trim();
        String outcrop = etOutcrop.getText().toString().trim();
        String pointMeaning = etPointMeaning.getText().toString().trim();
        String description = etDescription.getText().toString().trim();

        if (pointIdStr.isEmpty() || pointName.isEmpty()||timeStr.isEmpty() || outcrop.isEmpty() || pointMeaning.isEmpty() || description.isEmpty()) {
            Toast.makeText(this, "请填写所有必填项", Toast.LENGTH_SHORT).show();
            return;
        }

        int pointId;
        try {
            pointId = Integer.parseInt(pointIdStr);
        } catch (NumberFormatException e) {
            Toast.makeText(this, "点位序号必须是数字", Toast.LENGTH_SHORT).show();
            return;
        }

        Date recordTime;
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            recordTime = sdf.parse(timeStr);
        } catch (Exception e) {
            Toast.makeText(this, "时间格式错误 (yyyy-MM-dd HH:mm:ss)", Toast.LENGTH_SHORT).show();
            return;
        }

        if (longitude == 0.0 && latitude == 0.0) {
            Toast.makeText(this, "请先获取GPS坐标", Toast.LENGTH_SHORT).show();
            return;
        }

        if (outcrop.length() > 50 || pointMeaning.length() > 50 || description.length() > 500) {
            Toast.makeText(this, "露头/点义超50字，描述超500字", Toast.LENGTH_SHORT).show();
            return;
        }

        executor.execute(() -> {
            boolean renameExists = dbConnection.isNameExists(pointName);

            boolean success = dbConnection.update(pointId ,pointName ,recordTime, longitude, latitude, outcrop, pointMeaning, description, photo);
            runOnUiThread(() -> {
                Toast.makeText(this, success&&renameExists ? "数据修改成功" : "数据修改失败,请尝试联系管理", Toast.LENGTH_SHORT).show();
                if (success) {
                    clearInputs();
                }
            });
        });



    }



    private void connectToDatabase() {
        executor.execute(new Runnable() {
            @Override
            public void run() {
                boolean success = dbConnection.connect();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(Test1.this, success ? "数据库连接成功" : "数据库连接失败,检查网络或存本地数据库", Toast.LENGTH_SHORT).show();
                    }
                });
            }
        });
    }
//context
    private void disconnectFromDatabase() {
        executor.execute(() -> {
            dbConnection.disconnect();
            runOnUiThread(() -> Toast.makeText(this, "数据库已断开", Toast.LENGTH_SHORT).show());
        });
    }

    private void clearInputs() {
        etPointId.setText("");
        etRecordTime.setText("");

        etOutcrop.setText("");
        etPointMeaning.setText("");
        etDescription.setText("");
        longitude = 0.0;
        latitude = 0.0;
        photo = null;
        etgpsLatitude.setText("");
        etgpsLongitude.setText("");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        try {
            dbConnection.disconnect();
            if (!executor.isShutdown()) {
                executor.shutdown();
                executor.awaitTermination(5, TimeUnit.SECONDS);
            }
        } catch (InterruptedException e) {
            Toast.makeText(this, "清理失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }
}
